<template>
  <div>
    <el-card class="box-card">
      <!-- 标签页 -->
      <el-tabs v-model="activeName">
        <el-tab-pane label="用户管理" name="first" />
        <el-button type="primary" size="small" class="el-icon-plus btn" @click="add">新增角色</el-button>
      </el-tabs>
      <el-table
        :data="fromData"
        border
        height="350px"
        style="width: 100%"
      >
        <el-table-column
          prop="title"
          align="center"
          label="角色名称"
        />
        <el-table-column
          prop="description"
          align="center"
          label="描述"
        />
        <el-table-column
          prop="address"
          align="center"
          label="操作"
        >
          <template v-slot="scoped">
            <el-button size="mini" type="success" @click="assignPerm(scoped.row.id)">分配权限</el-button>
            <el-button size="mini" type="warning" @click="edit(scoped.row.id)">编辑角色</el-button>
            <el-button size="mini" type="danger" @click="del(scoped.row.id)">删除角色</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <div class="page">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="parameter._limit"
          @current-change="pageNum"
        />
      </div>
    </el-card>
    <!-- 编辑/添加弹窗 -->
    <el-dialog
      :title="id?'编辑角色':'新增角色'"
      :visible="isShowDialog"
      width="30%"
      @close="canCel"
    >
      <el-form ref="From" :model="dialogue" :rules="rules">
        <el-form-item label="标题" prop="title">
          <el-input v-model="dialogue.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="dialogue.description" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="btnOk">确定</el-button>
        <el-button @click="canCel">取消</el-button>
      </template>
    </el-dialog>

    <!-- 分配权限弹窗 -->
    <el-dialog title="分配权限" :visible="isShowPer" @close="btnPermCancel">
      <el-checkbox-group v-model="permInds">
        <el-tree
          :data="permsList"
          :props="{label:'title'}"
          default-expand-all
        >
          <template #default="{data}">
            <el-checkbox :label="data.id">
              {{ data.title }}
            </el-checkbox>
          </template>
        </el-tree>
      </el-checkbox-group>
      <template #footer>
        <el-button size="small" type="primary" @click="btnPermOk">确认</el-button>
        <el-button size="small" @click="btnPermCancel">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, addRole, delRole, editRole, editRoleDetails, getRoleNum } from '@/api/Role'
import { getPermsList } from '@/api/permission'
import { renderTree } from '@/utils'
export default {
  data() {
    return {
      isShowDialog: false, // 对话框
      activeName: 'first', // 标签页默认
      fromData: [], // 渲染列表
      parameter: {
        _limit: 5,
        _start: 0
      }, // 必传参数
      dialogue: {
        title: '', // 标题
        description: '' // 描述
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入描述', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ]
      },
      id: null,
      total: 0,
      Index: 0,
      // 分配权限相关变量
      isShowPer: false,
      permsList: [],
      permInds: [],
      roleDetail: {}
    }
  },
  created() {
    this.getList()
    /* 获取总条数 */
    this.getRoleList()
    // 获取所有权限
    this.getPermList()
  },
  methods: {
    /* 获取角色列表 */
    async getList() {
      const res = await getRoleList(this.parameter)
      console.log('角色列表', res)
      this.fromData = res.data
    },
    async getRoleList() {
      const res = await getRoleNum()
      this.total = res.data
      console.log(108, this.total)
    },
    // 获取所有权限列表
    async getPermList() {
      const res = await getPermsList()
      this.permsList = renderTree(res.data, '0')
    },
    /* 点击新增打开弹窗 */
    add() {
      this.isShowDialog = true
    },
    /* 关闭弹窗 */
    canCel() {
      this.dialogue = {
        title: '', // 标题
        description: '' // 描述
      }
      this.id = null
      this.isShowDialog = false
    },
    /* 确定按钮 */
    async btnOk() {
      try {
        /* 先校验表单 */
        await this.$refs.From.validate()
        if (this.dialogue.id) {
          await editRole({ ...this.dialogue, id: this.id })
          /* 提示用户 */
          this.$message.success('编辑成功')
        } else {
          /* 发送请求 */
          const res = await addRole(this.dialogue)
          console.log(res)
          this.fromData.data = res.data
          /* 提示用户 */
          this.$message.success('添加成功')
        }
        /* 关闭弹窗 */
        this.isShowDialog = false
        /* 更新页面 */
        this.getList()
        this.getRoleList()
        /* 清空表单 */
        this.dialogue = {
          title: '', // 标题
          description: '' // 描述
        }
      } catch (error) {
        console.log(error)
      }
    },
    /* 删除 */
    async del(id) {
      try {
        const res = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        if (res) {
          /* 发送请求 */
          await delRole(id)
          /* 提示用户 */
          this.$message.success('删除成功')
          if (this.Index !== 1 && this.fromData.length === 1) {
            this.Index--
          }
          this.parameter._start = (this.Index - 1) * this.parameter._limit
          /* 更新页面 */
          this.getList()
          /* 更新条数 */
          this.getRoleList()
        }
      } catch (error) {
        console.log(error)
      }
    },
    /* 编辑弹窗 */
    async edit(id) {
      this.id = id
      const res = await editRoleDetails(id)
      this.dialogue = res.data
      this.isShowDialog = true
    },
    // 分配权限
    async assignPerm(id) {
      const { data } = await editRoleDetails(id)
      console.log('角色详情', data)
      this.roleDetail = data
      const permArr = data.permissions
      console.log('权限列表', data.permissions)
      this.permInds = permArr.map(item => item.id)
      console.log(this.permInds)
      console.log(146, this.permsList)
      this.id = data.id
      // console.log('角色id', this.id  )
      this.isShowPer = true
    },
    // 分配弹窗确认按钮
    async btnPermOk() {
      const arr = []
      const res = await getPermsList()
      this.permInds.forEach(item1 => {
        res.data.forEach(item2 => {
          if (item1 === item2.id) {
            arr.push(item2)
          }
        })
      })
      const { data } = await editRole({ ...this.roleDetail, permissions: arr })
      // 通知用户
      this.$message.success('分配权限成功')
      console.log('246', data)
      // await
      this.isShowPer = false
    },
    // 分配弹窗取消按钮
    btnPermCancel() {
      this.isShowPer = false
    },
    /* 页码 */
    pageNum(index) {
      console.log(index)
      this.Index = index
      this.parameter._start = (index - 1) * this.parameter._limit
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
.page{
  margin-top: 10px;
  margin-left: 40%;
}
.el-tabs__content{
.btn{
    margin-bottom: 10px
}
}

</style>

